#!/bin/bash

die() {
    echo "$1"
    exit 1
}

if [ ! "$2" ]
then
    echo 'Use: mbs_rename_results <packet dir> <prefix>'
    exit 1
fi
PREFIX="$2"

cd "$1/results" || die "Packet $1 does not have a results directory."

# Now go through each .tar and extract/rename it
for i in *.tar
do
    PLATFORM="${i/.tar}"
    mkdir ${PREFIX}${PLATFORM} &&
    cd ${PREFIX}${PLATFORM} || die "Failed to create ${PREFIX}${PLATFORM}/"
    tar xf ../$i || die "Failed to extract $i."
    cd .. || die "Failed to cd out of ${PREFIX}${PLATFORM}."
    if [ "`echo $PLATFORM | grep windows`" ]
    then
        zip -r ${PREFIX}${PLATFORM}.zip ${PREFIX}${PLATFORM}/ || die "Failed to create ${PREFIX}${PLATFORM}.zip"
    else
        tar jcf ${PREFIX}${PLATFORM}.tar.bz2 ${PREFIX}${PLATFORM}/ || die "Failed to create ${PREFIX}${PLATFORM}.tar.bz2"
    fi
    rm -rf ${PREFIX}${PLATFORM}
done
